package com.loongtech.bi.action.newsystem;

import com.loongtech.bi.action.authManagement.ResultData;
import com.loongtech.bi.advertisment.controller.BaseAdvAction;
import com.loongtech.bi.advertisment.model.AdvWarnMacData;
import com.loongtech.bi.advertisment.service.PayUserService;
import com.loongtech.bi.manager.system.SyncInfoLogManager;
import com.loongtech.bi.support.ExcelUtils;
import com.loongtech.core.util.RetCode;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * ClassName: AdvWarningDataAction
 * 
 * @author liuchen
 * @Description: 广告积分墙录入
 * @date 2017-7-28 下午3:19:48
 */
@Controller
@Scope("prototype")
@RequestMapping("/advWarningData")
public class AdvWarningDataAction extends BaseAdvAction {

	private static final long serialVersionUID = 5441464438898384781L;

	@Resource(name = "payUserService")
	private PayUserService payUserService;

	@Resource(name = "systemConfig")
	private SystemConfig systemConfig;
	@Resource
	private SyncInfoLogManager syncInfoLogManager;

    @RequestMapping(value = "search.do", method = {RequestMethod.GET, RequestMethod.POST})
    public void search(HttpServletRequest request, HttpServletResponse response, @RequestParam Integer gameId, String callback) {
        try {
            Map<String, Object> result = new HashMap<String, Object>();
            List<AdvWarnMacData> datas = payUserService.getWarnMacData(gameId);
            result.put("res", "0");
            result.put("datas", datas);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> result = new HashMap<String, Object>();
            result.put("res", "1");
            result.put("msg", e.getMessage());
            printToJson(response, result, callback);
            return;
        }
    }

	@RequestMapping(value = "upload.do", method = { RequestMethod.POST })
	public ResultData<String> upload(@RequestParam(value = "file", required = false) CommonsMultipartFile file)
			throws IOException {
		System.out.println("upload file: ");
		if (file == null || file.getSize() <= 0 || file.getOriginalFilename() == null) {
			return new ResultData<>(RetCode.eEmptyUploadFile.getErrorcode(), RetCode.eEmptyUploadFile.getErrorMsg());
		}
		String fileName = file.getOriginalFilename();
		String id = UUID.randomUUID().toString();
		// 文件的相对路径
		String subPath = "AdvWarnData_" + id + "_" + fileName;
		// 文件的绝对路径
		String filePath = systemConfig.getFileParentPath() + subPath;
		File tmpdir = new File(systemConfig.getFileParentPath());
		if (!tmpdir.exists()) {
			tmpdir.mkdir();
		}
		File newfile = new File(filePath);
		try {
			FileUtils.copyInputStreamToFile(file.getInputStream(), newfile);
		} catch (IOException e) {
			e.printStackTrace();
			return new ResultData<>(RetCode.eIOUploadFile.getErrorcode(), RetCode.eIOUploadFile.getErrorMsg());
		}
		return parseExcel(newfile);
	}

	public ResultData<String> parseExcel(File file) {
		StringBuilder errorid = new StringBuilder();
		try {
			List<AdvWarnMacData> tmp = parseUploadedExcel(file);
			List<AdvWarnMacData> datas = new ArrayList<>();
			StringBuilder InsertSQLPre = new StringBuilder(
					"insert into td_adv_warning_mac(warntype,mac,kindtype,source) values  ");
			if (tmp != null && tmp.size() > 0) {
				Integer gameId = tmp.get(0).getGameId();
				List<AdvWarnMacData> list = payUserService.getWarnMacData(gameId);
				asd: for (AdvWarnMacData e : tmp) {
					for (AdvWarnMacData adv : list) {
						if (e.getMac().equals(adv.getMac())) {
							continue asd;
						} else {
							datas.add(e);
							InsertSQLPre.append("(3,'" + e.getMac() + "','" + e.getKindtype() + "','" + e.getSource()
									+ "'),");
							continue asd;
						}
					}
				}
				String isql = InsertSQLPre.substring(0, InsertSQLPre.length() - 1);
				syncInfoLogManager.add(tmp.get(0).getGameId().toString(), isql);
			}
			payUserService.batchAddMac(datas);
		} catch (Exception e) {
			e.printStackTrace();
			return new ResultData<>(RetCode.eParseExcel.getErrorcode(), RetCode.eParseExcel.getErrorMsg());
		} finally {
			if (file != null && file.exists()) {
				file.delete();
			}
		}
		if (errorid.length() > 0) {
			return new ResultData<>(RetCode.eSuccess.getErrorcode(), "解析成功！包含重复短链 ： "
					+ errorid.substring(0, errorid.length() - 1));
		} else {
			return ResultData.success();
		}
	}

	private List<AdvWarnMacData> parseUploadedExcel(File file) throws Exception {
		List<AdvWarnMacData> result = new ArrayList<>();
		InputStream input = new FileInputStream(file);
		Workbook wb = WorkbookFactory.create(input);
		Sheet tempSheet = wb.getSheetAt(0);
		if (tempSheet == null) {
			IOUtils.closeQuietly(input);
			System.out.println("Error---------------------------excel内容为空,数据错误！");
			throw new Exception("excel内容为空,数据错误");
		}
		int rowNum = tempSheet.getLastRowNum();// 获得总行数
		for (int i = 0; i <= rowNum; i++) {
			Row row = tempSheet.getRow(i);
			if (row == null) {
				continue;
			}
			String gameId = ExcelUtils.getCellValue(row.getCell(0));
			String mac = ExcelUtils.getCellValue(row.getCell(1));
			String kindtype = ExcelUtils.getCellValue(row.getCell(2));
			String source = ExcelUtils.getCellValue(row.getCell(3));

			if ("".equals(mac) || "".equals(kindtype) || "".equals(source) || "".equals(gameId)) {
				continue;
			}

			AdvWarnMacData e = new AdvWarnMacData();
			e.setGameId(Integer.parseInt(gameId));
			e.setMac(mac);
			e.setKindtype(kindtype);
			e.setSource(source);
			result.add(e);
		}
		IOUtils.closeQuietly(input);
		return result;
	}

}
